#include <func.h>

int main(int argc,char *argv[])
{
    ARGS_CHECK(argc,3);
    int sockfd;
    sockfd=socket(AF_INET,SOCK_DGRAM,0);
    ERROR_CHECK(sockfd,-1,"socket");
    printf("sockfd=%d\n",sockfd);
    struct sockaddr_in ser;
    bzero(&ser,sizeof(ser));
    ser.sin_family=AF_INET;
    ser.sin_addr.s_addr=inet_addr(argv[1]);
    ser.sin_port=htons(atoi(argv[2]));
    int ret;
    ret=connect(sockfd,(struct sockaddr*)&ser,sizeof(ser));
    ERROR_CHECK(ret,-1,"connect");
    socklen_t len=sizeof(struct sockaddr);
    char buf[1024]={0};
    read(STDIN_FILENO,buf,sizeof(buf));
    sendto(sockfd,buf,sizeof(buf)-1,0,(struct sockaddr*)&ser,len);
    fd_set t;
    while(1)
    {
        FD_ZERO(&t);
        FD_SET(sockfd,&t);
        FD_SET(STDIN_FILENO,&t);
        select(sockfd+1,&t,NULL,NULL,NULL);
        if(FD_ISSET(sockfd,&t))
        {
            bzero(buf,sizeof(buf));
            if(!recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL))
            {
                printf("GooBye!\n");
                break;
            }
            write(STDOUT_FILENO,buf,strlen(buf));
        }
        if(FD_ISSET(STDIN_FILENO,&t))
        {
            bzero(buf,sizeof(buf));
            read(STDIN_FILENO,buf,sizeof(buf));
            sendto(sockfd,buf,sizeof(buf)-1,0,(struct sockaddr*)&ser,len);
        }
    }
    return 0;
}

